package com.example.demo.service.sys.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.demo.dao.SysCaptchaDao;
import com.example.demo.entity.sys.SysCaptchaEntity;
import com.example.demo.service.sys.SysCaptchaService;
import com.google.code.kaptcha.Producer;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import sun.dc.pr.PRException;

import javax.annotation.Resource;
import java.awt.image.BufferedImage;
import java.util.Date;

/**
 * @ClassName SysCaptchaServiceImpl
 * @Description:
 * @Author liyunjiang
 * @Date 2020/5/13 22:09
 */
@Service("sysCaptchaService")
public class SysCaptchaServiceImpl extends ServiceImpl<SysCaptchaDao, SysCaptchaEntity> implements SysCaptchaService {
    @Resource
    Producer producer;
    @Override
    public BufferedImage getCaptcha(String uuid) throws PRException {
        if (StringUtils.isBlank(uuid)){
            throw new PRException("uuid不能为空");
        }
        String text = producer.createText();
        SysCaptchaEntity entity = new SysCaptchaEntity();
        entity.setUuid(uuid);
        entity.setCode(text);
        Date date = new Date();
        date.setTime(date.getTime() + 5);
        entity.setExpireTime(date);
        this.save(entity);
        return producer.createImage(text);
    }

    @Override
    public boolean validate(String uuid, String captcha) {
        SysCaptchaEntity captchaEntity = this.getOne(new QueryWrapper<SysCaptchaEntity>().eq("uuid", uuid));
        if (captchaEntity == null){
            return false;
        }
        // 删除数据库验证码
        this.removeById(uuid);
        if (captchaEntity.getCode().equals(captcha) && captchaEntity.getExpireTime().getTime() >= System.currentTimeMillis()){
            return true;
        }
        return false;
    }
}
